AC_DEFUN([AC_MIGEMO],
[
AC_ARG_WITH([migemo],
            AS_HELP_STRING([--with-migemo@<:@=prefix@:>@],
                           [specify migemo installed prefix (default is /usr/local)]),
            [want_migemo="yes"
             if test "$withval" = "yes"; then
               ac_migemo_prefix="/usr/local"
             elif test "$withval" = "no"; then
               want_migemo="no"
             else
               ac_migemo_prefix="$withval"
             fi],
            [want_migemo="no"
             ac_migemo_prefix="/usr/local"])

AC_ARG_VAR([MIGEMO_CFLAGS],
           [C compiler flags for migemo
            (default is -I<migemo_prefix>/include)])
AC_ARG_VAR([MIGEMO_LIBS],
           [linker flags for migemo
            (default is -L<migemo_prefix>/lib -lmigemo)])

if test "$want_migemo" = "yes"; then
  if test "$MIGEMO_CFLAGS" = ""; then
    MIGEMO_CFLAGS="-I$ac_migemo_prefix/include"
  fi
  if test "$MIGEMO_LIBS" = ""; then
    MIGEMO_LIBS="-L$ac_migemo_prefix/lib -lmigemo"
  fi

  CPPFLAGS_SAVED="$CPPFLAGS"
  CPPFLAGS="$CPPFLAGS $MIGEMO_CFLAGS"
  export CPPFLAGS

  LDFLAGS_SAVED="$LDFLAGS"
  LDFLAGS="$LDFLAGS $MIGEMO_LIBS"
  export LDFLAGS

  _tmp="$MIGEMO_LIBS"
  while test 1; do
    if test "${_tmp##-L*}" = ""; then
      _tmp_dir=`echo $_tmp | sed -e 's/^-L *\(@<:@^ @:>@*\).*$/\1/'`
      LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$_tmp_dir"
    fi
    if test "$_tmp" = "${_tmp#* }"; then
      break
    fi
    _tmp="${_tmp#* }"
  done
  export LD_LIBRARY_PATH

  AC_LANG_PUSH([C])
  AC_CHECK_HEADER([migemo.h], , [AC_MSG_ERROR([migemo.h is required])])
  if test "$1" != ""; then
    AC_MSG_CHECKING([for migemo version >= $1])
    CPPFLAGS="$CPPFLAGS -DMIGEMO_REQ=\"$1\""
    export CPPFLAGS
    AC_RUN_IFELSE(AC_LANG_PROGRAM([[
@%:@include <stdlib.h>
@%:@include <migemo.h>
int parse_ver_term(const char **c) {
  for(; **c && (**c < '0' || **c > '9'); ++*c);
  if (!**c) { return -1; }
  char *e = NULL;
  long res = strtol(*c, &e, 10);
  *c = e;
  return res;
}
]], [[
const char *ver = MIGEMO_VERSION;
const char *req = MIGEMO_REQ;
while(1) {
  int v = parse_ver_term(&ver);
  int r = parse_ver_term(&req);
  if (v < r) {
    return 1;
  } else if (r < 0) {
    break;
  }
}
]]),
                  [AC_MSG_RESULT([yes])],
                  [AC_MSG_RESULT([no])
                   AC_MSG_ERROR([C/Migemo version mismatch!])])
  fi
  AC_LANG_POP([C])

  CPPFLAGS="$CPPFLAGS_SAVED"
  LDFLAGS="$LDFLAGS_SAVED"

  ifelse([$2], , :, [$2])
else
  ifelse([$3], , :, [$3])
fi

AC_SUBST(MIGEMO_CFLAGS)
AC_SUBST(MIGEMO_LIBS)
])